﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using DMS.BaseClass;
using DMS.Business.Modules.Configuation;
using DMS.Business.Utility;
using DMS.BaseClass;
using DMS.Business.Modules.Organization;

namespace DMS.Web.Common.Controls
{
    public partial class ConfigSettingForSelector : ContentFormControlBase, IConfigSetting
    {
        private int _MaxValueCount = 100;
        public int MaxValueCount
        {
            get
            {
                return this._MaxValueCount;
            }
            set
            {
                this._MaxValueCount = value;
            }
        }
        private string _ValueTemplate = string.Empty;
        public string ValueTemplate
        {
            get
            {
                return this._ValueTemplate;
            }
            set
            {
                this._ValueTemplate = value;
            }
        }
        private string _DefaultValue = string.Empty;
        public string DefaultValue
        {
            get
            {
                return this._DefaultValue;
            }
            set
            {
                this._DefaultValue = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.EnsureChildControls();
            }
        }

        #region IConfigSetting Members
        public string ConfigID
        {
            get
            {
                return this.hidConfigID.Value;
            }
            set
            {
                this.hidConfigID.Value = value;
            }
        }

        public string MemberID
        {
            get
            {
                return this.hidMemberID.Value;
            }
            set
            {
                this.hidMemberID.Value = value;
            }
        }

        public string MemberType
        {
            get
            {
                return this.hidMemberType.Value;
            }
            set
            {
                this.hidMemberType.Value = value;
            }
        }

        public void InitForm()
        {
            if (string.IsNullOrEmpty(this.MemberID))
            {
                this.InitSysConfigForm();
            }
            else
            {
                this.InitMemberConfigForm();
            }
        }

        public void Save()
        {
            if (string.IsNullOrEmpty(this.MemberID))
            {
                this.SaveSysConfigForm();
            }
            else
            {
                this.SaveMemberconfigForm();
            }
        }

        #endregion

        #region 界面逻辑
        private void InitValueSelector()
        {
            if (!string.IsNullOrEmpty(this.ValueTemplate))
            {
                this.ddlConfigValueList.Items.Clear();
                if (this.ValueTemplate.ToUpper().IndexOf("#DAY:") == 0)
                {
                    int begintTime = 0;
                    int endTime = 24;
                    int step = 60;
                    string[] paramInfo = this.ValueTemplate.Substring(5).Split(",".ToCharArray());
                    begintTime = Convert.ToInt32(paramInfo[0]);
                    endTime = Convert.ToInt32(paramInfo[1]);
                    step = Convert.ToInt32(paramInfo[2]);

                    DateTime counter = DateTime.Now.Date;
                    int c = 0;
                    while (counter < DateTime.Now.Date.AddDays(1) && c < this.MaxValueCount)
                    {
                        ListItem item = new ListItem();
                        item.Text = string.Format("{0}:{1}", counter.Hour.ToString("00"), counter.Minute.ToString("00"));
                        item.Value = item.Text;

                        this.ddlConfigValueList.Items.Add(item);
                        counter = counter.AddMinutes((double)step);
                        c++;
                    }
                }
                else
                {
                    string[] valueArray = this.ValueTemplate.Split("#".ToCharArray());
                    foreach (string valueItem in valueArray)
                    {
                        string[] itemInfo = valueItem.Split(":".ToCharArray());
                        if (itemInfo.Length == 2)
                        {
                            ListItem item = new ListItem();
                            item.Text = itemInfo[0];
                            item.Value = itemInfo[1];

                            this.ddlConfigValueList.Items.Add(item);
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(this.DefaultValue) && this.ddlConfigValueList.Items.Count > 0)
            {
                this.SetSelectedItem(this.DefaultValue);
            }
        }
                
        private void InitSysConfigForm()
        {
            SysConfig config = ConfigHelper.GetSysConfigByID(this.ConfigID);
            if (config != null)
            {
                this.lblConfigTitle.Text = config.Name;
                this.SetSelectedItem(config.Value);
            }
        }
        private void InitMemberConfigForm()
        {
            SysConfig defaultConfig = null;
            MemberConfig config = ConfigHelper.GetMemberConfig(MemberID, this.ConfigID);
            if (config != null)
            {
                defaultConfig = config.Default;
                this.lblConfigTitle.Text = config.Name;
                this.SetSelectedItem(config.Value);
            }
            else
            {
                defaultConfig = ConfigHelper.GetSysConfigByID(this.ConfigID);
                if (defaultConfig != null)
                {
                    this.lblConfigTitle.Text = defaultConfig.Name;
                    this.SetSelectedItem(defaultConfig.Value);
                }
                else
                {
                    ClientHelper.Instance.Alert("读取默认配置项时出错，请联系管理员。");
                }
            }
        }
        private void SaveSysConfigForm()
        {
        }
        private void SaveMemberconfigForm()
        {

            List<MemberConfig> memberConfigs = ConfigHelper.GetMemberConfigs(MemberID);
            MemberConfig config = (from c in memberConfigs
                                   where c.ID == this.ConfigID
                                   select c).ToList().DefaultIfEmpty(null).FirstOrDefault();
            if (config == null)
            {
                Actor actor = null;
                ActorTypes actorType = (ActorTypes)Enum.Parse(typeof(ActorTypes), this.MemberType);
                switch (actorType)
                {
                    case ActorTypes.Dept:
                        actor = UserHelper.GetDepartmentByID(MemberID) as Actor;
                        break;
                    case ActorTypes.Role:
                        actor = UserHelper.GetRoleByID(MemberID) as Actor;
                        break;
                    case ActorTypes.User:
                        actor = UserHelper.GetUserByID(MemberID) as Actor;
                        break;
                    case ActorTypes.SupplierAccount:
                        actor = SupplierHelper.GetAccountByID(MemberID) as Actor;
                        break;
                    case ActorTypes.Supplier:
                        actor = SupplierHelper.GetSupplierByID(MemberID) as Actor;
                        break;
                }
                
                SysConfig defaultConfig = ConfigHelper.GetSysConfigByID(this.ConfigID);
                if (actor != null)
                {
                    config = new MemberConfig(actor, defaultConfig);
                }
                else
                {
                    LogicException ex = new LogicException("保存成员配置时，找不到成员实例，请检查成员类型或成员数据。");
                    LogHelper.LogException(ex);
                }
            }

            if (config != null)
            {
                config.Value = this.ddlConfigValueList.SelectedValue;
                config.Save();
            }
        }
        private void SetSelectedItem(string value)
        {
            this.EnsureChildControls();
            ListItem item = this.ddlConfigValueList.Items.FindByValue(value.Trim());
            if (item != null)
            {
                this.ddlConfigValueList.SelectedValue = value;
            }
        }
        protected override void EnsureChildControls()
        {
            if (this.ddlConfigValueList.Items.Count == 0)
            {
                this.InitValueSelector();
            }

            base.EnsureChildControls();
        }
        #endregion
    }
}